package TopList;

import jHaggis.jHaggis;
import jHaggis.jTransScrollPane;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JFrame;
import javax.swing.JLabel;

import Lobby.mLobby;
import Player.mPlayer;
/**
 * @author Christopher Vogel
 */	
public class jToplist extends jHaggis implements Observer {

	private int rank=1;
	private mLobby model;
	JLabel table;
	jTransScrollPane scrollPane;

	
	public jToplist(mLobby model) {
		super("TopListe - Haggis - powered by Future App Lab");
		model.addObserver(this);
		this.setResizable(false);
		Dimension windowSize = new Dimension(500,400);
		this.setSize(windowSize);
		
		Font toplistFont = new Font("Arial", Font.PLAIN, 25);
		this.content.setFont(toplistFont);
		this.content.setForeground(Color.white);
		this.content.setLayout(new FlowLayout());
		this.model = model;
		this.model.addObserver(this);
			
		
		table = new JLabel();
		table.setFont(toplistFont);
		table.setForeground(Color.white);
		
		
		scrollPane = new jTransScrollPane(table);
		scrollPane.setPreferredSize(new Dimension(windowSize.width-30, windowSize.height-80));
		this.content.add(scrollPane);
		this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		this.setVisible(false);
	}
	
	
	private String Titles()	{
		return "<tr><th>Rank</th><th>Username</th><th>Points</th><th>Games</th></tr>";
	}
	private String Row(String Name, int Points, int Games)	{
		this.rank++;
		return "<tr><td>#"+(this.rank)+"</td><td>"+Name+"</td><td>"+Points+"</td><td>"+Games+"</td></tr>";
		
	}

	public void initTable(ArrayList<mPlayer> pl) {
		String rows="";
		this.rank=0;
		int i = 1;
		for (mPlayer p: pl) {
			rows+=Row(p.getUserName(), p.getPoints(), p.getPlayedGames());
			i++;
		}
		
		int h = i * 50 + 10;
		if (h>800) { h=800; }
		Dimension windowSize = new Dimension(500,h);
		this.setSize(windowSize);
		scrollPane.setPreferredSize(new Dimension(windowSize.width-30, windowSize.height-70));
		
		
		String html = "<html><table>"+Titles()+rows+"</table></html>";
		this.table.setText(html);
		
	}
	
	@Override
	public void update(Observable arg0, Object arg1) {
		// TODO Auto-generated method stub
		if (arg1.equals("Toplist")) {
			initTable(model.getToplistPlayers());
		}
	}

}
